<template>
  <div>
    <div class="center-w">
      <div class="head">
        <div class="title">公司管理</div>
        <div class="add">
          <el-button type="danger" @click="addCompany">添加公司</el-button>
          <el-input
            @input="inputChange"
            v-model="inputName"
            placeholder="请输入公司名"
            style="width: 150px; "
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>

      <el-table size="small" :data="CompanyData">
        <el-table-column show-overflow-tooltip align="center" label="公司名">
          <template slot-scope="scope">
            <span>{{ scope.row.name || "无" }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="公司负责人">
          <template slot-scope="scope">
            <span>{{ scope.row.headUserName || "无" }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="numberOfPerson" align="center" label="公司人数">
          <template slot-scope="scope">
            <span>{{ scope.row.numberOfPerson }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="balance" align="center" label="余额">
          <template slot-scope="scope">
            <span style="color:red">{{ scope.row.balance }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="updateTime"
          show-overflow-tooltip
          align="center"
          label="更新时间"
        ></el-table-column>

        <el-table-column
          fixed="right"
          align="center"
          width="300px"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="editCompany(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="success"
              @click="balanceClick(scope.row)"
              >充值</el-button
            >
            <el-button size="mini" type="warning" @click="runCompany(scope.row)"
              >记录</el-button
            >
            <!-- <el-button size="mini" type="danger" @click="delCompany(scope.row)"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 公司添加编辑弹窗 -->
      <el-dialog
        :title="currentTitle"
        :visible.sync="addAccountDialogVisible"
        width="60%"
        :before-close="closeForm"
      >
        <div class="sex">
          <el-form
            :model="dialogCompany"
            status-icon
            :rules="rules"
            ref="ruleForm"
            class="demo-ruleForm"
          >
            <div class="company_container">
              <div class="collection">
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-suitcase-1"></i>
                      </div>
                      <div style="margin-left: 10px;">公司名</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <el-form-item
                      prop="name"
                      label-width="0"
                      style="width: 100%;margin: 0 auto;"
                    >
                      <el-input
                        v-model="dialogCompany.name"
                        style="width: 100%;"
                      ></el-input>
                    </el-form-item>
                  </div>
                </div>
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-user"></i>
                      </div>
                      <div style="margin-left: 10px;">负责人</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <el-form-item
                      prop="headUser"
                      label-width="0"
                      style="width: 100%;margin: 0 auto;"
                    >
                      <el-select
                        style="width: 100%;"
                        v-model="dialogCompany.headUser"
                        filterable
                        remote
                        placeholder="请输入用户微信名"
                        :remote-method="remoteMethod"
                        :loading="loading"
                      >
                        <el-option
                          v-for="item in list"
                          :key="item.id"
                          :label="item.wxName"
                          :value="item.id"
                        >
                          <div
                            style="display:flex;justify-content:space-between"
                          >
                            <el-image
                              style="width: 30px; height: 30px;"
                              :src="item.img"
                            ></el-image>
                            <span>{{ item.wxName }}</span>
                          </div>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </div>
              <div class="collection" v-if="currentTitle === '编辑'">
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-time"></i>
                      </div>
                      <div style="margin-left: 10px;">创建时间</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <div class="content">{{ dialogCompany.createTime }}</div>
                  </div>
                </div>
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-coin"></i>
                      </div>
                      <div style="margin-left: 10px;">公司余额</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <div class="content" style="color: red;">
                      {{ dialogCompany.balance }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="collection" v-if="currentTitle === '编辑'">
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-connection"></i>
                      </div>
                      <div style="margin-left: 10px;">上级分销名称</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <div class="content">{{ dialogCompany.agentName }}</div>
                  </div>
                </div>
                <div class="company_item">
                  <div class="item_left">
                    <div class="label">
                      <div>
                        <i class="el-icon-takeaway-box"></i>
                      </div>
                      <div style="margin-left: 10px;">主体分销名称</div>
                    </div>
                  </div>
                  <div class="item_right">
                    <div class="content">
                      {{ dialogCompany.agentCompanyName || "无" }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="company_item" style="width: 100%;">
                <div class="item_left">
                  <div class="label">
                    <div>
                      <i class="el-icon-s-custom"></i>
                    </div>
                    <div style="margin-left: 10px;">成员管理</div>
                  </div>
                </div>
                <div class="item_right">
                  <el-form-item
                    prop="userMembers"
                    label-width="0"
                    style="width: 100%;margin: 0 auto;"
                  >
                    <el-select
                      style="width: 100%"
                      v-model="dialogCompany.userMembers"
                      multiple
                      filterable
                      remote
                      reserve-keyword
                      placeholder=""
                      :remote-method="remoteMethod"
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in list"
                        :key="item.id"
                        :label="item.wxName"
                        :value="item.id"
                      >
                        <div style="display:flex;justify-content:space-between">
                          <el-image
                            style="width: 30px; height: 30px;"
                            :src="item.img"
                          ></el-image>
                          <span>{{ item.wxName }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
              <div class="company_item" style="width: 100%;">
                <div class="item_left">
                  <div class="label">
                    <div>
                      <i class="el-icon-location-information"></i>
                    </div>
                    <div style="margin-left: 10px;">公司地址</div>
                  </div>
                </div>
                <div class="item_right">
                  <el-input
                    type="textarea"
                    v-model="dialogCompany.address"
                    style="width: 100%;"
                  ></el-input>
                </div>
              </div>
              <div class="company_item" style="width: 100%;">
                <div class="item_left">
                  <div class="label" style="height: 200px;">
                    <div>
                      <i class="el-icon-upload"></i>
                    </div>
                    <div style="margin-left: 10px;">公司小程序logo</div>
                  </div>
                </div>
                <div class="item_right" style="padding: 20px;">
                  <template>
                    <upload-img
                      :limit="1"
                      :value="dialogCompany.personUrl"
                      @input="uploadImgBack($event)"
                    />
                  </template>
                </div>
              </div>
              <div
                class="company_item"
                style="width: 100%;border-bottom: none;"
              >
                <div class="item_left">
                  <div class="label" style="height: 104px;">
                    <div>
                      <i class="el-icon-notebook-1"></i>
                    </div>
                    <div style="margin-left: 10px;">备注</div>
                  </div>
                </div>
                <div class="item_right">
                  <el-input
                    type="textarea"
                    v-model="dialogCompany.description"
                    style="width: 100%;"
                    :rows="3"
                    autocomplete="off"
                    maxlength="200"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="addAccountDialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="addUserNumber('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 公司流水弹窗 -->
      <el-dialog
        :title="runTableDialogTitle + ` 消费记录`"
        :visible.sync="runTableDialogVisible"
        width="50%"
      >
        <div class="runTable-w">
          <div class="runTable">
            <div style="margin-bottom:20px;color:#df6969">
              余额：{{ companyId.balance }}
            </div>
            <el-table size="samll" :data="tableData" border style="width: 100%">
              <el-table-column
                prop="rechargeCenterType"
                align="center"
                label="类型"
                width="60"
              >
                <template slot-scope="scope">
                  <div :style="scope.row.rechargeCenterType">
                    {{ scope.row.rechargeCenterType | rechargeCenterTypeTrans }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="totalAmount"
                align="center"
                label="金额"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="wxName"
                show-overflow-tooltip
                align="center"
                label="成员"
              >
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.wxName || "/" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="orderNo"
                show-overflow-tooltip
                align="center"
                label="单号"
              >
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.orderNo || "/" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="notes"
                align="center"
                label="备注"
              >
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.notes || "/" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" align="center" label="时间">
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
          </div>
          <Pagination
            v-bind:child-msg="pageparmS"
            @callFather="callFatherS"
          ></Pagination>
        </div>
      </el-dialog>

      <!-- 充值弹窗 -->
      <el-dialog
        title="充值"
        :visible.sync="balanceDialogVisible"
        :before-close="closeFormBalance"
        width="20%"
      >
        <el-form
          :model="balanceAddForm"
          status-icon
          :rules="BalanceRules"
          ref="balanceRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="到账金额：" prop="amount">
            <el-input
              v-model="balanceAddForm.amount"
              placeholder="请输入到账金额"
              style="width: 230px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="赠送金额：" prop="giftAmount">
            <el-input
              v-model="balanceAddForm.giftAmount"
              placeholder="请输入赠送金额"
              style="width: 230px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注：" prop="notes">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              v-model="balanceAddForm.notes"
              style="width: 230px;"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="balanceAdd('balanceRuleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 分页组件 -->
      <Pagination
        v-bind:child-msg="pageparmB"
        @callFather="callFatherB"
      ></Pagination>
    </div>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import uploadImg from "../../components/uploadImg";
import { getUserList } from "../../api/user";
import { rechargeList } from "../../api/recharge";

import {
  companyFind,
  companyDetail,
  comapnyCreate,
  companyUpdate,
  companyDelete,
  Recharge
} from "../../api/company";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入公司名"));
      } else {
        callback();
      }
    };

    var validateAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入到账金额"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      list: [],
      companyId: "",
      // 充值金额
      balanceAddForm: {
        amount: "",
        giftAmount: "",
        notes: ""
      },
      // 列表数据
      CompanyData: [],
      //搜索
      inputName: "",
      // 分页
      pageparmB: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      pageparmS: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      // 弹窗表格
      tableData: [],
      // 弹框控制
      addAccountDialogVisible: false,
      runTableDialogVisible: false,
      balanceDialogVisible: false,
      //弹框标题
      currentTitle: "",
      runTableDialogTitle: "",
      //弹框表单
      dialogCompany: {
        balance: "",
        createTime: "",
        description: "",
        headUser: "",
        id: "",
        name: "",
        numberOfPerson: "",
        updateTime: "",
        userMembers: "",
        address: "",
        personUrl: [
          {
            url:
              "http://applet.atptest.com/gTbSE31p1719307785927.png?v=1719307786373"
          }
        ]
      },
      rules: {
        name: [{ validator: validatePass, trigger: ["blur"] }]
      },
      BalanceRules: {
        amount: [
          { validator: validateAmount, trigger: ["blur"] },
          {
            pattern: /^(-?\d+)\.?(\d*)$/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        giftAmount: [
          {
            pattern: /^(-?\d+)\.?(\d*)$/,
            message: "请输入数字",
            trigger: "blur"
          }
        ]
      }
    };
  },
  components: {
    Pagination,
    uploadImg //上传图片
  },

  created() {
    this._companyFind();
    this._getUserList();
  },

  watch: {
    "dialogCompany.headUser"(val) {
      if (val == 1) {
        this.list = [];
      }
    }
  },

  filters: {
    rechargeCenterTypeTrans: function(rechargeCenterType) {
      switch (rechargeCenterType) {
        case 0:
          return "充值";
        case 1:
          return "消费";
        default:
          return "null";
      }
    }
  },

  methods: {
    // 用户列表模糊查询
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this._getUserList(query);
        }, 200);
      } else {
        this.list = [];
      }
    },

    // 上传图片的回调
    uploadImgBack(x) {
      let urlList = x.map(v => {
        return { url: v.url, state: 0 };
      });
      this.dialogCompany.personUrl = urlList;
    },

    // 获取用户列表数据
    async _getUserList(e) {
      let data = {
        pageIndex: 1,
        size: 999,
        name: e ? e : ""
      };
      let res = await getUserList(data);
      if (res.code == 200) {
        this.list = res.data ? res.data.items : [];
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },

    // 获取公司列表数据
    async _companyFind() {
      let parm = {
        searchKey: this.inputName,
        pageIndex: this.pageparmB.pageIndex,
        pageSize: this.pageparmB.pageSize
      };
      let res = await companyFind(parm);
      if (res.data) {
        const { items, totalCount } = res.data;
        this.pageparmB.total = totalCount;
        this.CompanyData = items;
      } else {
        this.CompanyData = [];
      }
    },

    //获取流水列表数据
    async _rechargeList() {
      let data = {
        pageIndex: this.pageparmS.pageIndex,
        pageSize: this.pageparmS.pageSize,
        companyid: this.companyId.id
      };
      let res = await rechargeList(data);
      if (res.data) {
        const { items, totalCount } = res.data;
        this.pageparmS.total = totalCount;
        this.tableData = items;
      } else {
        this.tableData = [];
      }
    },

    //添加公司弹窗
    addCompany() {
      this.dialogCompany.personUrl = [
        {
          url:
            "http://applet.atptest.com/gTbSE31p1719307785927.png?v=1719307786373"
        }
      ];
      this.addAccountDialogVisible = true;
      this.currentTitle = "添加公司";
    },

    //编辑回显数据
    async editCompany(e) {
      this.addAccountDialogVisible = true;
      this.currentTitle = "编辑";
      // 获取详情
      let res = await companyDetail({ id: e.id });
      let userMembers = res.data.userMembers.map(item => {
        return item.item1;
      });
      this.dialogCompany = {
        balance: res.data.balance,
        createTime: res.data.createTime,
        updateTime: res.data.updateTime,
        description: res.data.description,
        headUser: res.data.headUser ? res.data.headUser.item1 : "",
        id: res.data.id,
        name: res.data.name,
        numberOfPerson: res.data.numberOfPerson,
        userMembers,
        address: res.data.address,
        agentName: res.data.agentName,
        agentCompanyName: res.data.agentCompanyName,
        personUrl: res.data.personUrl
          ? [{ url: res.data.personUrl }]
          : [
              {
                url:
                  "http://applet.atptest.com/gTbSE31p1719307785927.png?v=1719307786373"
              }
            ]
      };
    },

    //流水
    runCompany(e) {
      this.runTableDialogVisible = true;
      this.runTableDialogTitle = e.name;
      this.companyId = e;
      this._rechargeList();
    },

    //删除
    delCompany(e) {
      this.$confirm(`您确定要删除吗？`, "删除确认", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 确定操作
          companyDelete({ companyId: e.id }).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this._companyFind();
            } else {
              this._companyFind();
            }
          });
        })
        .catch(() => {
          // 取消操作
          this.$message.info("取消删除");
        });
    },

    // 查询
    inputChange() {
      this._companyFind();
    },

    // 余额充值弹窗
    balanceClick(e) {
      this.balanceDialogVisible = true;
      this.companyId = e;
    },

    //确认添加公司
    addUserNumber(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.dialogCompany.personUrl instanceof Array) {
            this.dialogCompany.personUrl =
              this.dialogCompany.personUrl.length > 0
                ? this.dialogCompany.personUrl[0].url
                : "";
          }
          if (!this.dialogCompany.personUrl) {
            this.$message.error("公司小程序logo不能为空");
            return;
          }
          if (this.currentTitle == "添加公司") {
            let data = {
              numberOfPerson: this.dialogCompany.userMembers.length,
              name: this.dialogCompany.name,
              headUserId: this.dialogCompany.headUser || 0,
              userMemberIds: this.dialogCompany.userMembers,
              description: this.dialogCompany.description,
              address: this.dialogCompany.address,
              personUrl: this.dialogCompany.personUrl
            };
            comapnyCreate(data).then(res => {
              if (res.code == 200) {
                this.$message.success("新增成功");
                this.addAccountDialogVisible = false;
                this._companyFind();
              }
            });
          } else {
            let data = {
              name: this.dialogCompany.name,
              numberOfPerson: this.dialogCompany.userMembers.length,
              headUserId: this.dialogCompany.headUser || 0,
              userMemberIds: this.dialogCompany.userMembers,
              description: this.dialogCompany.description,
              id: this.dialogCompany.id,
              address: this.dialogCompany.address,
              personUrl: this.dialogCompany.personUrl
            };
            companyUpdate(data).then(res => {
              if (res.code == 200) {
                this.$message.success("编辑成功");
                this.addAccountDialogVisible = false;
                this._companyFind();
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    // 充值确认
    balanceAdd(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          let data = {
            companyId: this.companyId.id,
            amount: Number(this.balanceAddForm.amount),
            giftAmount: Number(this.balanceAddForm.giftAmount),
            totalAmount:
              Number(this.balanceAddForm.amount) +
              Number(this.balanceAddForm.giftAmount),
            notes: this.balanceAddForm.notes
          };
          Recharge(data).then(res => {
            if (res.code == 200) {
              this.$message.success("充值成功！");
              this.balanceDialogVisible = false;
              (this.balanceAddForm = {
                amount: "",
                giftAmount: "",
                notes: ""
              }),
                this._companyFind();
            }
          });
        }
      });
    },

    // 弹窗关闭校验
    closeForm(done) {
      this.$refs["ruleForm"].resetFields();
      this.dialogCompany = {
        balance: "",
        createTime: "",
        description: "",
        headUser: "",
        id: "",
        name: "",
        numberOfPerson: "",
        updateTime: "",
        userMembers: "",
        agentName: "",
        agentCompanyName: ""
      };
      done();
    },
    closeFormBalance(done) {
      this.$refs["balanceRuleForm"].resetFields();
      (this.balanceAddForm = {
        amount: "",
        giftAmount: "",
        notes: ""
      }),
        done();
    },

    // 分页插件事件
    callFatherB(parm) {
      this.pageparmB.pageIndex = parm.pageIndex;
      this.pageparmB.pageSize = parm.size;
      this._companyFind();
    },
    callFatherS(parm) {
      this.pageparmS.pageIndex = parm.pageIndex;
      this.pageparmS.pageSize = parm.size;
      this._rechargeList();
    }
  }
};
</script>

<style lang="less" scoped>
.company_container {
  width: 100%;
  border-top: 1px solid rgb(235, 238, 245);
  border-right: 1px solid rgb(235, 238, 245);
  border-bottom: 1px solid rgb(235, 238, 245);
  .collection {
    display: flex;
    width: 100%;
  }
  .company_item {
    display: flex;
    align-items: center;
    width: 50%;

    border-bottom: 1px solid rgb(235, 238, 245);
    .item_left {
      display: flex;
      align-items: center;
      height: 100%;

      .label {
        width: 154px;
        min-height: 70px;
        display: flex;
        align-items: center;
        color: rgb(126, 126, 126);
        font-family: 思源黑体;
        font-weight: 500;
        background: rgb(250, 250, 250);
        padding-left: 14px;
        box-sizing: border-box;
        border-left: 1px solid rgb(235, 238, 245);
        border-right: 1px solid rgb(235, 238, 245);
      }
    }
    .item_right {
      width: 100%;
      display: flex;
      align-items: center;
      padding: 0 14px;
      .content {
        color: rgb(91, 91, 91);
        font-family: 思源黑体;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
}

/deep/ .el-form-item .el-form-item__content {
  width: 100%;
  padding: 0px !important;
  margin-right: 0;
}
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 82vh;
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
}

.title {
  color: rgba(16, 16, 16, 1);
  font-size: 20px;
  margin-bottom: 20px;
}

.add {
  .el-input {
    margin-left: 20px;
  }
}

.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.runTable {
  width: 100%;
  height: 570px !important;
  overflow-y: scroll;
}

.runTable-w {
  height: 600px;
}
.balanceAdd {
  display: flex;
  height: 60px;
  line-height: 60px;
  .one {
    width: 80px;
  }
  .two {
    flex: 1;
  }
}

// .el-input {
//   max-width: 300px;
//   margin-right: 30px;
// }
// .el-select {
//   max-width: 300px;
//   margin-right: 30px;
// }

.head-img {
  /* border-radius: 50%; */
  width: 30px;
  height: 30px;
}
/deep/ .el-dialog__body {
  padding: 10px 20px 30px;
}
</style>
